package com.ff.controller;

import com.ff.common.R;



import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("upload")
    public R<String> upload(MultipartFile file){
        String oldName = file.getOriginalFilename();
        String suffix = oldName.substring(oldName.lastIndexOf("."));

        String newName=UUID.randomUUID()+""+suffix;

        File f=new File(basePath);
        if (!f.exists()){
            f.mkdirs();
        }

        File filePath=new File(f,newName);
        try {
            //将临时文件转存到指定位置
            file.transferTo(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(newName);
    }
    @GetMapping("download")
    public void download(String name,HttpServletResponse response){
        response.setContentType("image/jpeg");
        try {
            byte[] bytes = FileUtils.readFileToByteArray(new File(basePath + name));
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
